package main;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Properties;

import render.RaytracerImage;
import render.Scene;

public class RenderApplet extends Applet {

	private static final long serialVersionUID = -4924906232081940457L;
	
	private static Properties properties;
	
	private RaytracerImage render;
	private Scene scene;
	
	
	public static void main(String[] args) {
		
		TracerProperties props = null;		
		if (args.length > 0) {
			props = new TracerProperties(args[0]);			
		} else {
			props = new TracerProperties();
			props.storeDefaults();
		}
		properties = props;
		
		if (args.length > 1) {
			RaytracerImage render = new RaytracerImage(props, null);
			render.draw(new SampleScene());
			render.save(args[1]);
		} else {
			final RenderApplet applet = new RenderApplet();
			
			Frame frame = new Frame("Raytracer");				
	        frame.addWindowListener(new WindowAdapter() {
	            @Override
	            public void windowClosing(WindowEvent e) { System.exit(0); }
	        });
	        
	        frame.add(applet);        
	        frame.setPreferredSize(new Dimension(
	    		Integer.parseInt(props.getProperty("output_width", "640")),
	    		Integer.parseInt(props.getProperty("output_height", "480"))
	        ));
	        frame.setResizable(false);
	        frame.pack();
			frame.setVisible(true);
			
			applet.init();
			applet.start();
		}
		
		//ObjectModel.createModel("C:\\Users\\chris\\Documents\\uni\\WiSe08-09\\cg1\\ex\\ex03\\cg1_ex3\\meshes\\head.off");
	}


	@Override
	public void init() {
		render = new RaytracerImage(properties, this);
		scene = new SampleScene2();
	}

	@Override
	public void start() {
		// since this function may be invoked by a system thread, we perform our heavy calculations in a separate (program) thread
		new Thread() {
			@Override
			public void run() {
				long start = System.currentTimeMillis();
				// draw scene to render buffer
				render.draw(scene);
				
				// write render time to render buffer
				render.getGraphics().setColor(Color.BLACK);
				render.getGraphics().drawString("Render time : " + (System.currentTimeMillis() - start) + " ms", 10, 10);

				// invoke repaint
				repaint();
			}
		}.start();
	}

	@Override
	public void stop() {

	}

	@Override
	public void update(Graphics g) {
		paint(g);
	}


	@Override
	public void paint(Graphics g) {
		// draw render buffer		
		g.drawImage(render, 0, 0, null);
	}
	
	
}